package com.jsyxdl.k3cloud.listener.handling;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.ty.basic.exception.message.SystemErrorCodeEnum;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 物料批量提交审核
 */
public class SubmissionAndReviewHanding {
    /**
     * 反审核
     * @param numbers 单据编码集合，数组类型
     * @return ERP接口返回的JSON格式
     * @throws Exception
     */
    public static JSONObject unSubmittReview(Map<String, Object> executionType, List<String> numbers) throws Exception {

        //构建批量反审核数据

        String jsonObj = "{\n" +
                "    \"CreateOrgId\": 0,\n" +
                "    \"Numbers\": [],\n" +
                "    \"Ids\": \"\",\n" +
                "    \"SelectedPostId\": 0,\n" +
                "    \"UseOrgId\": 0,\n" +
                "    \"NetworkCtrl\": \"\",\n" +
                "    \"IgnoreInterationFlag\": \"\"\n" +
                "}";
        JSONObject sendJson = JSONObject.parseObject(jsonObj);
        sendJson.put("Numbers", numbers);
        JSONObject erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, sendJson);

        if (erpResult.containsKey("Result")) {
            JSONObject Result = erpResult.getJSONObject("Result");
            if (Result.containsKey("ResponseStatus")) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
            }
        }

        return erpResult;
    }

    /**
     * 提交审核
     * @param executionType 接口对象属性
     * @param numbers 单据编码集合，数组类型
     * @return ERP接口返回的JSON格式
     * @throws Exception
     */
    public static JSONObject submittReview(Map<String, Object> executionType, List<String> numbers) throws Exception {
        if (numbers.size() == 0) {
            JSONObject httpResult = new JSONObject();
            JSONObject resultObj = new JSONObject();
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("IsSuccess", true);
            responseStatus.put("msg", executionType.get("formid") + " 数据为空");
            resultObj.put("ResponseStatus", responseStatus);
            httpResult.put("Result", resultObj);
            return httpResult;
        }
        //构建批量提交数据，发送ERP审核BOM

        String jsonObj = "{\n" +
                "    \"CreateOrgId\": 0,\n" +
                "    \"Numbers\": [],\n" +
                "    \"Ids\": \"\",\n" +
                "    \"SelectedPostId\": 0,\n" +
                "    \"UseOrgId\": 0,\n" +
                "    \"NetworkCtrl\": \"\",\n" +
                "    \"IgnoreInterationFlag\": \"\"\n" +
                "}";
        JSONObject sendJson = JSONObject.parseObject(jsonObj);
        List<String> list = new ArrayList<>();
        list.addAll(numbers);
        sendJson.put("Numbers", numbers);
        executionType.put("uri", "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        JSONObject erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, sendJson);

        if (erpResult.containsKey("Result")) {
            JSONObject Result = erpResult.getJSONObject("Result");
            if (Result.containsKey("ResponseStatus")) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
            }
        }
        //构建批量审核数据，发送ERP审核BOM

        String autditStr = "{\n" +
                "    \"CreateOrgId\": 0,\n" +
                "    \"Numbers\": [],\n" +
                "    \"Ids\": \"\",\n" +
                "    \"InterationFlags\": \"\",\n" +
                "    \"UseOrgId\": 0,\n" +
                "    \"NetworkCtrl\": \"\",\n" +
                "    \"IsVerifyProcInst\": \"true\",\n" +
                "    \"IgnoreInterationFlag\": \"\",\n" +
                "    \"UseBatControlTimes\": \"false\"\n" +
                "}";
        executionType.put("code","SH0000009X");
        JSONObject autditJson = JSONObject.parseObject(autditStr);
        autditJson.put("Numbers", list);
        executionType.put("uri", "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, autditJson);

        return erpResult;
    }


    /**
     * 提交审核按ID作为依据
     * @param executionType 接口对象属性
     * @param ids 单据id集合，数组类型
     * @return ERP接口返回的JSON格式
     * @throws Exception
     */
    public static JSONObject submittReviewByIds(Map<String, Object> executionType, List<String> ids) throws Exception {
        if (ids.size() == 0) {
            JSONObject httpResult = new JSONObject();
            JSONObject resultObj = new JSONObject();
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("IsSuccess", true);
            responseStatus.put("msg", executionType.get("formid") + " 数据为空");
            resultObj.put("ResponseStatus", responseStatus);
            httpResult.put("Result", resultObj);
            return httpResult;
        }
        //构建批量提交数据，发送ERP审核BOM

        String jsonObj = "{\n" +
                "    \"CreateOrgId\": 0,\n" +
                "    \"Numbers\": [],\n" +
                "    \"Ids\": \"\",\n" +
                "    \"SelectedPostId\": 0,\n" +
                "    \"UseOrgId\": 0,\n" +
                "    \"NetworkCtrl\": \"\",\n" +
                "    \"IgnoreInterationFlag\": \"\"\n" +
                "}";
        JSONObject sendJson = JSONObject.parseObject(jsonObj);
        StringBuilder stringBuilder=new StringBuilder();
        for(int a=0;a<ids.size();a++){
            if(a>0) stringBuilder.append(",");
            stringBuilder.append(ids.get(a));
        }
        sendJson.put("Ids", stringBuilder.toString());

        executionType.put("uri", "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        JSONObject erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, sendJson);

        if (erpResult.containsKey("Result")) {
            JSONObject Result = erpResult.getJSONObject("Result");
            if (Result.containsKey("ResponseStatus")) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
            }
        }
        //构建批量审核数据，发送ERP审核BOM

        String autditStr = "{\n" +
                "    \"CreateOrgId\": 0,\n" +
                "    \"Numbers\": [],\n" +
                "    \"Ids\": \"\",\n" +
                "    \"InterationFlags\": \"\",\n" +
                "    \"UseOrgId\": 0,\n" +
                "    \"NetworkCtrl\": \"\",\n" +
                "    \"IsVerifyProcInst\": \"true\",\n" +
                "    \"IgnoreInterationFlag\": \"\",\n" +
                "    \"UseBatControlTimes\": \"false\"\n" +
                "}";
        executionType.put("code","SH0000009X");

        JSONObject autditJson = JSONObject.parseObject(autditStr);
        autditJson.put("Ids", stringBuilder.toString());
        executionType.put("uri", "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, autditJson);

        return erpResult;
    }

    /**
     * 提交
     * @param executionType 接口对象属性
     * @param numbers 单据编码集合，数组类型
     * @return ERP接口返回的JSON格式
     * @throws Exception
     */
    public static JSONObject submitt(Map<String, Object> executionType, List<String> numbers) throws Exception {
        if (numbers.size() == 0) {
            JSONObject httpResult = new JSONObject();
            JSONObject resultObj = new JSONObject();
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("IsSuccess", true);
            responseStatus.put("msg", executionType.get("formid") + " 数据为空");
            resultObj.put("ResponseStatus", responseStatus);
            httpResult.put("Result", resultObj);
            return httpResult;
        }
        //构建批量提交数据，发送ERP审核BOM

        String jsonObj = "{\n" +
                "    \"CreateOrgId\": 0,\n" +
                "    \"Numbers\": [],\n" +
                "    \"Ids\": \"\",\n" +
                "    \"SelectedPostId\": 0,\n" +
                "    \"UseOrgId\": 0,\n" +
                "    \"NetworkCtrl\": \"\",\n" +
                "    \"IgnoreInterationFlag\": \"\"\n" +
                "}";
        JSONObject sendJson = JSONObject.parseObject(jsonObj);
        List<String> list = new ArrayList<>();
        list.addAll(numbers);
        sendJson.put("Numbers", numbers);
        executionType.put("uri", "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        JSONObject erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, sendJson);

        if (erpResult.containsKey("Result")) {
            JSONObject Result = erpResult.getJSONObject("Result");
            if (Result.containsKey("ResponseStatus")) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
            }
        }
        return erpResult;
    }

    /**
     * 禁用
     * @param executionType 接口对象属性
     * @param numbers 单据编码集合，数组类型
     * @return ERP接口返回的JSON格式
     * @throws Exception
     */
    public static JSONObject Disabled(Map<String, Object> executionType, List<String> numbers) throws Exception {
        if (numbers.size() == 0) {
            JSONObject httpResult = new JSONObject();
            JSONObject resultObj = new JSONObject();
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("IsSuccess", true);
            responseStatus.put("msg", executionType.get("formid") + " 数据为空");
            resultObj.put("ResponseStatus", responseStatus);
            httpResult.put("Result", resultObj);
            return httpResult;
        }
        //构建批量提交数据，发送ERP审核BOM
        List<JSONObject> jsonList=getErpBOM(numbers,executionType);

        Map<String,Object> out=new LinkedHashMap<>();
        out.put("CreateOrgId",0);
        out.put("Numbers",new ArrayList<>());
        out.put("PkEntryIds",new ArrayList<>());
        out.put("UseOrgId",0);
        out.put("NetworkCtrl","");
        out.put("IgnoreInterationFlag","");

        StringBuilder stringBuilder=new StringBuilder();
        for(int i=0;i<jsonList.size();i++){
            if(i>0) stringBuilder.append(",");
            stringBuilder.append(jsonList.get(i).getString("FID"));
        }
        out.put("Ids",stringBuilder.toString());
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject httpResult=new JSONObject();
        httpResult.put("IsSuccessByAPI",true);
        Map<String, Object> outParameter = new HashMap<>();

        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            outParameter.put("formid", "ENG_BOM");
            outParameter.put("data", JSONObject.toJSONString(out));
            outParameter.put("opNumber","Forbid");

            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/k3cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/k3cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/k3cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }
        }

        String plm_code= (String) executionType.get("plm_code");


        if (httpResult.containsKey("Result")) {
            JSONObject Result = httpResult.getJSONObject("Result");
            if (Result.containsKey("ResponseStatus")) {
                JSONObject responseStatus = Result.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if(responseStatus.containsKey("Errors")){
                        JSONArray Errors=responseStatus.getJSONArray("Errors");
                        boolean isError=false;
                        JSONArray SuccessEntitys=new JSONArray();
                        String erp_process="";

                        for(int a=0;a<Errors.size();a++){
                            JSONObject err=Errors.getJSONObject(a);
                            if(err.containsKey("Message")){
                                String Message=err.getString("Message");
                                if(Message.endsWith("的物料清单，数据已经禁用!")){
                                    String errStr=Message;
                                    erp_process = errStr.replaceAll("[^a-zA-Z0-9_.]", "");
                                    JSONObject obj=new JSONObject();
                                    obj.put("Number",erp_process);
                                    SuccessEntitys.add(obj);
                                    Errors.remove(a);
                                    a--;
                                }
                                else{
                                    isError=true;
                                }
                            }
                        }

                        if(isError){
                            k3CloudHttpService.saveLogs(plm_code,erp_process,"失败",responseStatus.toJSONString(),JSONObject.toJSONString(outParameter),"禁用接口","");
                            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                                    responseStatus.get("Errors").toString());
                        }
                        else{
                            JSONObject resultObj=new JSONObject();
                            JSONObject plmStatus=new JSONObject();
                            plmStatus.put("IsSuccess",true);
                            plmStatus.put("msg",String.format("禁用成功%s",erp_process));
                            plmStatus.put("SuccessEntitys",SuccessEntitys);
                            resultObj.put("ResponseStatus",plmStatus);
                            httpResult.put("Result",resultObj);
                            k3CloudHttpService.saveLogs(plm_code,erp_process,"成功",responseStatus.toJSONString(),JSONObject.toJSONString(outParameter),"禁用接口","");
                            return httpResult;
                        }
                    }
                }
                else{
                    JSONArray successEntitys = responseStatus.getJSONArray("SuccessEntitys");
                    String erpNumber="";
                    if (successEntitys.size() > 0) {
                        erpNumber = successEntitys.getJSONObject(0).getString("FNumber");
                    }
                    k3CloudHttpService.saveLogs(plm_code,erpNumber,"成功",responseStatus.toJSONString(),JSONObject.toJSONString(outParameter),"禁用接口","");
                }
            }
        }
        return httpResult;
    }

    /**
     * 读取ERP物料清单数据
     *
     * @param objectNumbers
     * @return
     * @throws Exception
     */
    public static List<JSONObject> getErpBOM(List<String> objectNumbers, Map<String, Object> executionType)
            throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();

        String json="{\n" +
                "    \"FormId\": \"ENG_BOM\",\n" +
                "    \"FieldKeys\": \"FMaterialId.FNumber,FID\",\n" +
                "    \"FilterString\": [{\"FieldName\":\"FMATERIALID.FNumber\",\"Compare\":\"67\",\"Value\":\"CP0102005558\",\"Left\":\"\",\"Right\":\"\",\"Logic\":0}],\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";

        outMap=JSONObject.parseObject(json);
        JSONArray FilterString =new JSONArray();
        for(int i=0;i<objectNumbers.size();i++){
            JSONObject filter=new JSONObject();
            filter.put("FieldName","FMATERIALID.FNumber");
            filter.put("Compare","67");
            filter.put("Left","");
            filter.put("Right","");
            filter.put("Logic",0);
            filter.put("Value",objectNumbers.get(i));
            FilterString.add(filter);
        }
        outMap.put("FilterString",FilterString);



        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI",true);
        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "STK_Inventory");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }

            List<JSONObject> list = new ArrayList<>();
            if (httpResult != null) {
                if (httpResult.containsKey("Result") == false && httpResult.containsKey("messages")) {
                    JSONArray resultList = httpResult.getJSONArray("messages");
                    for (int i = 0; i < resultList.size(); i++) {
                        JSONArray value = resultList.getJSONArray(i);
                        JSONObject entity = new JSONObject();
                        entity.put("FID", value.get(1));
                        list.add(entity);
                    }
                    return list;
                }
            }
        }

        return null;
    }
}
